<?php


namespace app\api\controller;


use app\api\model\Cart as CartModel;

class Sao extends Controller{
    /* @var \app\api\model\User $user */
    private $user;

    /* @var \app\api\model\Cart $model */
    private $model;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();
        $this->model = new CartModel($this->user);
    }
    public function index($result){
        $arrayResult = explode('|',$result);
        $arrayResultCount = count($arrayResult);
        switch ($arrayResultCount) {
            case 1:
                $goodsSn = $arrayResult[0];
                //商品编码获取条形码
                $goodsStockInfo = db('goods_stock')->where('bar_code = '.$goodsSn.'')->whereOr('goods_num = '.$goodsSn.'')->find();
                break;
            case 2:
                $goodsSn = $arrayResult[1];
                //商品编码
                $goodsStockInfo = db('goods_stock')->where('goods_num = '.$goodsSn.'')->find();
                break;
            case  3:
                $goodsId = $arrayResult[2];
                //商品库存id
                $goodsStockInfo = db('goods_stock')->where('id = '.$goodsId.'')->find();

                break;
        }
        if($goodsStockInfo) {
            $goodsNum = $goodsStockInfo['goods_num'];
            $goodsSkuInfo = db('goods_sku')->where('goods_no = ' . $goodsNum)->find();
            if (!empty($goodsSkuInfo)) {
                if (!$this->model->add($goodsSkuInfo['goods_id'], 1, $goodsSkuInfo['goods_sku_id'])) {
                    return $this->renderError($this->model->getError() ?: '加入购物车失败');
                }
                // 购物车商品总数量
                $totalNum = $this->model->getGoodsNum();
                return $this->renderSuccess(['cart_total_num' => $totalNum], '加入购物车成功');
            } else {
                return $this->renderError('该商品未找到！');
            }
        }else{
            return $this->renderError('该商品未找到！');
        }
    }
}